﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using webApi;

namespace YYS.Controllers
{
    public class pcController : ControlerEx
    {
        public static void RegisterBundles(System.Web.Optimization.BundleCollection bundles)
        {
            bundles.Add(new System.Web.Optimization.ScriptBundle("~/Content/pc/index").Include("~/Views/pc/index.js").WithLastModifiedToken());
            bundles.Add(new System.Web.Optimization.ScriptBundle("~/Content/pc/Login").Include("~/Views/pc/Login.js").WithLastModifiedToken());

            bundles.Add(new System.Web.Optimization.ScriptBundle("~/Content/pc/videoShare").Include("~/Views/pc/helper/video.share.js").WithLastModifiedToken());
        }
        #region 字典
        readonly Dictionary<string, string> courseMap = new Dictionary<string, string>()
        {
            { "FnBSI_ID", "bsiId" },
            { "FsUI_OptorName", "oiName"},
            { "schId", "schId" },
            { "schTitle", "schTitle"},
            { "schDate", "schDate" },
            { "schMark", "schMark"},
            { "openId", "openId" },
            { "schTime", "schTime"},

            { "msId", "msId" },
            { "msDate", "msDate" },
            { "msMark", "msMark"},
            { "msTime", "msTime"},

            //TSC_CourseInfoList  
            { "FnCIL_ID", "cilId" },
            { "FsCIL_Name", "cilName" },
            { "FsCIL_Require", "cilRequire" },
            { "FfCIL_ClassHour", "cilClassHour" },
            { "FdCIL_StartTime", "cilStartTime" },
            { "FdCIL_FinishTime", "cilFinishTime" },
            { "FsCIL_CoverPath", "cilCoverPath" },
            { "FnCIL_Status", "cilStatus" },
            { "FdCIL_MakeTime", "makeTime" },
            { "CLRXml", "clrList" },
            { "SummaryXml", "mediaList" },

            { "FdCLI_StartTime", "cliStartTime" },
            { "FdCLI_FinishTime", "cliFinishTime" },
            { "FsLI_Name", "liName" },

            { "aHasTask", "aHasTask" },
            { "aWeek", "aWeek" },
            { "aDate", "aDate" },
        };

        Dictionary<string, object> _courseToDictionary(System.Data.SqlClient.SqlDataReader sdr)
        {
            return sdr.xToDictionary(this.courseMap, formater: (key, value, _this) =>
            {
                switch (key)
                {
                    //上课时间
                    case "FdCLI_StartTime":
                    case "FdCLI_FinishTime":
                        return value.xFormatDateTime("HH:mm");
                    //选课周期
                    case "FdCPI_SelectFinishTime":
                    case "FdCPI_SelectStartTime":
                        return value.xFormatDateTime("yyyy-MM-dd HH:mm");
                    case "FdCPI_StartTime":
                    case "FdCPI_FinishTime":
                    case "FdHI_Date": //节假日日期
                    case "schDate":
                    case "aDate":
                    case "msDate":
                        return value.xFormatDateTime("yyyy-MM-dd");
                    case "FdCIL_StartTime":
                    case "FdCIL_FinishTime":
                        {
                            if (key == "FdCIL_FinishTime")
                            {
                                var v = value.xTrim().xToDatetime();
                                _this["cilIsExpire"] = v.HasValue && v.Value < DateTime.Now;
                            }
                            return value.xFormatDateTime("yyyy-MM-dd");
                        }
                    case "CanSelect":
                        {
                            if (value.xTrim() == "1")
                            {
                                var v = sdr.xSdrValue("FdCPI_SelectStartTime").xTrim().xToDatetime();
                                var countDown = v.HasValue ? v.Value.Subtract(DateTime.Now).TotalMilliseconds : 0;
                                _this["countDown"] = countDown > 0 ? countDown : 0;
                            }
                        }
                        break;
                    case "FdCIL_MakeTime":
                    case "schTime":
                    case "msTime":
                        return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                    case "GradeXml":
                        {
                            var str = value.xTrim();
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                try
                                {
                                    var xel = str.xToXElement();
                                    return xel.Elements().Select(x => new
                                    {
                                        giId = x.xXmlValue<int>("FnGI_ID"),
                                        giName = x.xXmlValue("FsGI_Name")
                                    });
                                }
                                catch { }
                            }
                            return new object[] { };
                        }
                    case "ClassXml":
                        {
                            var str = value.xTrim();
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                try
                                {
                                    var xel = str.xToXElement();
                                    return xel.Elements().Select(x => new
                                    {
                                        ciId = x.xXmlValue<int>("FnCI_ID"),
                                        ciName = x.xXmlValue("FsCI_Name")
                                    });
                                }
                                catch { }
                            }
                            return new object[] { };
                        }
                    case "MoneyXml":
                        {
                            _this["HasMust"] = 0;
                            _this["MustFeeSum"] = 0;
                            var str = value.xTrim();
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                try
                                {
                                    var xel = str.xToXElement();
                                    var list = xel.Elements().Select(x => new
                                    {
                                        cmrId = x.xXmlValue<int>("FnCMR_ID"),
                                        cmrName = x.xXmlValue("FsCMR_Name"),
                                        cmrPrice = x.xXmlValue<decimal>("FfCMR_Price", 0M).ToString("F2"),
                                        cmrIsMust = x.xXmlValue<int>("FnCMR_IsMust", 0),
                                        cmrRemark = x.xXmlValue("FsCMR_Remark"),
                                        cplPayStatus = x.xXmlValue<int>("FnCPL_PayStatus", -1),
                                        cplPayCount = x.xXmlValue<int>("FnCPL_PayCount", 0),
                                        oiName = x.xXmlValue("FsUI_OptorName")
                                    }).ToList();
                                    _this["HasMust"] = list.Exists(x => x.cmrIsMust == 1) ? 1 : 0;
                                    _this["MustFeeSum"] = list.Where(x => x.cmrIsMust == 1).Sum(x => decimal.Parse(x.cmrPrice)).ToString("F2");
                                    return list;
                                }
                                catch { }
                            }
                            return new object[] { };
                        }
                    case "CDTXml":
                        {
                            var str = value.xTrim();
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                try
                                {
                                    var xel = str.xToXElement();
                                    return xel.Elements().Select(x => new
                                    {
                                        uiId = x.xXmlValue<int>("FnUI_ID"),
                                        uiName = x.xXmlValue("FsUI_Name")
                                    });
                                }
                                catch { }
                            }
                            return new object[] { };
                        }
                    case "CLRXml":
                        {
                            var str = value.xTrim();
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                try
                                {
                                    var xel = str.xToXElement();
                                    return xel.Elements().Select(x => new
                                    {
                                        clrWeek = x.xXmlValue<int>("FnCLR_Week"),
                                        liName = x.xXmlValue("FsLI_Name").xTrim(),
                                        cliStartTime = x.xXmlValue("FdCLI_StartTime").xFormatDateTime("HH:mm"),
                                        cliFinishTime = x.xXmlValue("FdCLI_FinishTime").xFormatDateTime("HH:mm"),
                                        clrWeekStr = GetWeekDay(x.xXmlValue<int>("FnCLR_Week"))
                                    });
                                }
                                catch { }
                            }
                            return new object[] { };
                        }
                    case "SummaryXml":
                        {
                            var str = value.xTrim();
                            if (!string.IsNullOrWhiteSpace(str))
                            {
                                try
                                {
                                    var xel = str.xToXElement();
                                    return xel.Elements().Select(x => new
                                    {
                                        miId = x.xXmlValue<int>("FnMI_ID"),
                                        miTitle = x.xXmlValue("FsMI_Title").xTrim(),
                                        miType = x.xXmlValue<int>("FnMI_Type"),
                                        miIndex = x.xXmlValue<int>("FnMI_Index"),
                                        miDuration = x.xXmlValue("FsMI_Duration").xTrim(),
                                        miUrl = x.xXmlValue("FsMI_Url").xTrim(),
                                        miSize = x.xXmlValue("FsMI_Size").xTrim()
                                    });
                                }
                                catch { }
                            }
                            return new object[] { };
                        }
                }
                return value;
            });
        }
        #endregion
        // GET: pc
        public ActionResult Index()
        {
            Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
            return View("~/Views/pc/index.cshtml");
        }
        public ActionResult Login()
        {
            Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
            return View("~/Views/pc/Login.cshtml");
        }

        #region 获取vue组件 template 和 script
        /* 示例
             <template>
                <div>
                    <component is="style" />
                    <p>{{a}}</p>
                    <template></template>
                </div>    
            </template>
            <script>
                module = {
                    data: function () {
                        return {
                            a: new Date()
                        };
                    }
                };
            </script>
            <style>
                p { color: red; }
            </style>
        */

        [HttpPost]
        public ActionResult vueComponent()
        {
            var name = Request.Form["name"].xTrim();
            if (string.IsNullOrWhiteSpace(name)) return backJson(1, "404.1 - 页面不存在");

            var controlerName = RouteData.Values["controller"].xTrim();
            var viewPath = "~/Views/" + controlerName + "/" + name + ".cshtml";
            var context = this.ControllerContext;
            var result = ViewEngines.Engines.FindPartialView(context, viewPath);
            if (result.View == null) return backJson(1, "404.2 - 页面不存在");

            try
            {
                string text = "";
                using (var ms = new System.IO.MemoryStream())
                {
                    using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(ms, System.Text.Encoding.UTF8))
                    {
                        ViewContext viewContext = new ViewContext(context, result.View, this.ViewData, this.TempData, streamWriter);
                        viewContext.View.Render(viewContext, streamWriter);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }

                    var bytes = ms.ToArray();
                    text = System.Text.Encoding.UTF8.GetString(bytes);
                }
                string template = "", script = "", style = "";

                var g = new System.Text.RegularExpressions.Regex(@"<template[^>]*>([\s\S]*)<\/template>", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(text);
                if (g.Success)
                {
                    text = text.Replace(g.Value, "");
                    if (g.Groups.Count > 1) template = Compress(g.Groups[1].Value);
                }

                g = new System.Text.RegularExpressions.Regex(@"<script[^>]*>([\s\S]*?)<\/script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(text);
                if (g.Success && g.Groups.Count > 1) script = new Microsoft.Ajax.Utilities.Minifier().MinifyJavaScript(g.Groups[1].Value);

                g = new System.Text.RegularExpressions.Regex(@"<style[^>]*>([\s\S]*?)<\/style>", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(text);
                if (g.Success && g.Groups.Count > 1) style = new Microsoft.Ajax.Utilities.Minifier().MinifyStyleSheet(g.Groups[1].Value);

                template = template.Replace("<component is=\"style\" />", "<component is=\"style\" scoped type=\"text/css\">" + style + "</component>");

                return backJson(0, null, new { template = template.xToBase64(), script = script.xToBase64() });
            }
            catch (Exception ex)
            {
                return backJson(1, ex.Message);
            }
            //return PartialView(viewPath);
        }
        /// <summary>
        /// 压缩html代码
        /// </summary>
        /// <param name="text">html代码</param>
        /// <returns></returns>
        private static string Compress(string text)
        {
            var reg = new System.Text.RegularExpressions.Regex(@"\s*(</?[^\s/>]+[^>]*>)\s+(</?[^\s/>]+[^>]*>)\s*");
            text = reg.Replace(text, m => m.Groups[1].Value + m.Groups[2].Value);
            //移除html标签之间的空格 
            text = new System.Text.RegularExpressions.Regex(@"(?<=>)[\s|\n|\t]*(?=<)").Replace(text, string.Empty);
            //移除多余空格和换行符
            text = new System.Text.RegularExpressions.Regex(@"\n+\s+").Replace(text, string.Empty);
            return text;
        }
        #endregion

        [HttpPost]
        [v3Authorize()]
        public JsonResult GetUrlToBase64()
        {
            var url = Request.Form["url"].xTrim();
            var list = new List<object>();
            try
            {
                System.Net.WebClient mywebclient = new System.Net.WebClient();
                byte[] Bytes = mywebclient.DownloadData(url);
                string Base64string = "data:image/jpeg;base64," + Convert.ToBase64String(Bytes);

                var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
                db.CmdText = "SELECT * FROM dbo.MediaInfo WHERE FsMI_ImgUrl = @FsMI_ImgUrl AND FsMI_GroupKey IN ('72CC2905-6A49-46F9-9598-7391B2F7667D','5F4349DE-0EC3-4872-9509-A1A1C15FA47D','AD097CE4-F018-488C-BCD3-4240A0B23BFA')";
                db.IsProc = false;
                db.AddParameter("@FsMI_ImgUrl", SqlDbType.VarChar, url, 1024);
                db.NeedOutError = true;
                db.FuncRead = sdr =>
                {
                    list.Add(_TomediaList(sdr));
                };
                db.Exec();
                if (db.HasError) return _DBERROR(db);
                if (list.Count > 0) return backJson(1, "该媒体已经存在：" + url, Base64string);
                return backJson(0, null, Base64string);
            }
            catch (Exception e)
            {
                return backJson(1, "转base64失败:" + e.Message, url);
            }
        }

        #region 阿里云直传签名
        public static JsonResult _ossToken(string ossKey)
        {
            ossKey = ossKey.xTrim().TrimStart('/').TrimEnd('/');
            if (string.IsNullOrWhiteSpace(ossKey)) ossKey = DateTime.Now.ToString("yyyy/MM/dd");
            try
            {
                var now = DateTime.Now;
                string savekey = ossKey;
                var oss = Helper.GetAliOssConfig();
                Aliyun.OSS.OssClient client = new Aliyun.OSS.OssClient(oss.hostName, oss.accessKeyId, oss.accessKeySecret);
                DateTime ex = now.AddSeconds(600);
                Aliyun.OSS.PolicyConditions policyConds = new Aliyun.OSS.PolicyConditions();
                policyConds.AddConditionItem("content-length-range", 0L, 104857600L);
                policyConds.AddConditionItem(Aliyun.OSS.MatchMode.StartWith, "key", savekey);

                String postPolicy = client.GeneratePostPolicy(ex, policyConds);
                byte[] binaryData = System.Text.Encoding.Default.GetBytes(postPolicy);
                String encodedPolicy = Convert.ToBase64String(binaryData);
                var hmac = new System.Security.Cryptography.HMACSHA1(System.Text.Encoding.UTF8.GetBytes(oss.accessKeySecret));
                var hashBytes = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(encodedPolicy));
                var Signature = Convert.ToBase64String(hashBytes);

                return backJson(new
                {
                    code = 0,
                    errmsg = "",
                    accessKeyId = oss.accessKeyId,
                    policy = encodedPolicy,
                    signature = Signature,
                    key = savekey,
                    success_action_status = 200,
                    host = oss.hostName.Replace("http://", "https://"),
                    expire = ex.jToUnix().ToString()
                });
            }
            catch (Exception ex)
            {
                return backJson(1, ex.Message);
            }
        }
        #endregion 阿里云直传签名

        #region 删除阿里云图片
        [HttpPost]
        public JsonResult _ossDel()
        {
            var flag = Request.Form["flag"].xTo<int>();// 0 图片/视频  1 共享空间
            var miId = Request.Form["miId"].xTo<int>();
            //https://ynz1901.oss-cnhttps://40k6300z85.oicp.vip/api/pc/WxMpLogin/x_r2UUFO9cAEpTCoQgxcW1_vtJp3GaDFR0LjDnnJQVnlmna_gDyx4g5MqTzl2Nw8h_qDvEVG1jYHSYDgqUI8WQ-shanghai.aliyuncs.com/helper/%E6%98%9F%E5%A5%B3-%E6%94%BE%E7%BA%B5L.mp3https://40k6300z85.oicp.vip/api/pc/WxMpLogin/x_r2UUFO9cAEpTCoQgxcW1_vtJp3GaDFR0LjDnnJQVnlmna_gDyx4g5MqTzl2Nw8h_qDvEVG1jYHSYDgqUI8WQ
            var url = Request.Form["url"].Trim();//填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
            url = url.Replace("https://ynz1901.oss-cn-shanghai.aliyuncs.com/", "");

            var oss = Helper.GetAliOssConfig();
            Aliyun.OSS.OssClient client = new Aliyun.OSS.OssClient(oss.endpoint, oss.accessKeyId, oss.accessKeySecret);
            try
            {
                // 删除文件。
                client.DeleteObject(oss.bucketName, url);
            }
            catch (Exception ex)
            {
                return backJson(1, "Delete object failed." + ex.Message);
            }
            if (miId <= 0) return backJson(0, "");
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = flag == 0 ? "DELETE FROM dbo.MediaInfo WHERE FnMI_ID = @FnMI_ID" : "DELETE FROM dbo.TA_O_MediaInfo WHERE FnMI_ID = @FnMI_ID";
            db.AddParameter("@FnMI_ID", SqlDbType.Int, miId);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, "");
        }
        #endregion 删除阿里云图片

        #region 上传文件
        [HttpPost]
        [v3Authorize()]
        public JsonResult v3OssToken()
        {
            var folder = Request.Form["folder"].xTrim();
            if (string.IsNullOrWhiteSpace(folder)) folder = "hxt";
            folder = folder.TrimStart('/').TrimEnd('/');
            return _ossToken(folder + "/{0:yyyy/MM/dd}".xFormat(DateTime.Now));
        }
        #endregion 上传文件

        #region 获取当前用户
       
        //v3获取当前用户 v3Authorize OnAuthorization
        public static ResultObj<YYSService.unifiedUser> v3getCurrentUser(string openId, int source = 0)
        {
            var data = new ResultObj<YYSService.unifiedUser>();
            if (openId == null) return data.SetError("会话已超时.exp");
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_getCurrentUser";
            db.IsProc = true;
            db.AddParameter("@openId", System.Data.SqlDbType.NVarChar, openId, -1);
            db.AddParameter("@source", System.Data.SqlDbType.Int, source);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data.Obj = sdr.xTo<YYSService.unifiedUser>();
            };
            db.Exec();
            if (db.HasError) return data.SetError(db.Error);
            return data;
        }
        #endregion 获取当前用户

        #region 网页登录
        //网页登录
        [HttpPost]
        public ActionResult webLogin()
        {
            var account = Request.Form["account"].xTrim();
            var pwd = Request.Form["pwd"].xTrim();
            var data = new YYSService.unifiedUser();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_webLogin";
            db.IsProc = true;
            db.AddParameter("@account", SqlDbType.NVarChar, account, 50);
            db.AddParameter("@pwd", SqlDbType.NVarChar, pwd, 50);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = sdr.xTo<YYSService.unifiedUser>();
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            //TimeSpan slidingExpirationTime = TimeSpan.FromMinutes(300); // 例如30分钟
            //CacheHelper.AddLogin("openId", data["openId"].ToString(), DateTimeOffset.UtcNow.Add(slidingExpirationTime));
            return backJson(0, null, data);
        }
        [HttpPost]
        public static ResultObj<YYSService.unifiedUser> _webLogin(string account, string pwd)
        {
            var data = new ResultObj<YYSService.unifiedUser>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_webLogin";
            db.IsProc = true;
            db.AddParameter("@account", SqlDbType.NVarChar, account, 50);
            db.AddParameter("@pwd", SqlDbType.NVarChar, pwd, 50);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data.Obj =sdr.xTo<YYSService.unifiedUser>();
            };
            db.Exec();
            if (db.HasError) return data.SetError(db.HasSystemError ? db.Error : db.Error);
            //TimeSpan slidingExpirationTime = TimeSpan.FromMinutes(300); // 例如30分钟
            //CacheHelper.AddLogin("openId", data["openId"].ToString(), DateTimeOffset.UtcNow.Add(slidingExpirationTime));
            return data;
        }
        #endregion 网页登录

        #region PC
        #region 媒体集
        #region 字典
        static Dictionary<string, object> _TographicImg(System.Data.SqlClient.SqlDataReader sdr)
        {
            var _helperDoc = new Dictionary<string, string>()
            {
                { "id","id" } ,{ "title","title" },{ "url","url" }
                ,{ "desc","desc" } ,{ "MediaList","mediaList" }
            };

            return sdr.xToDictionary(_helperDoc, null, formater: (key, value, _this) =>
            {
                if (key == "FdHD_CreateTime" || key == "FdHD_MakeTime")
                {
                    return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                }
                if (key == "MediaList")
                {
                    if (value.xTrim().xIsNullOrEmpty()) return new object[] { };
                    System.Xml.Linq.XElement xel;
                    try
                    {
                        xel = value.xTrim().ConvertToXElement();
                    }
                    catch
                    {
                        return new object[] { };
                    }

                    return xel.Elements().Select(x => new
                    {
                        url = x.xXmlValue<string>("url")
                    });
                }
                return value;
            });
        }
        Dictionary<string, object> _TomediaInfoTitle(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["id"] = "id",
                ["text"] = "text",
                ["url"] = "url",
                ["groupKey"] = "groupKey",
                ["title"] = "title",
                ["show"] = "show",
                ["type"] = "type",
                ["mianUrl"] = "mianUrl",
                ["isMain"] = "isMain"
            };
            var data = sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                return value;
            });
            return data;
        }
        Dictionary<string, object> _TomediaList(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["FnMI_ID"] = "miId",
                ["FnMI_Type"] = "FnMI_Type",
                ["FsMI_Title"] = "miTitle",
                ["FsMI_Duration"] = "miDuration",
                ["FsMI_ImgBase64"] = "miImgBase64",
                ["FsMI_ImgUrl"] = "miImgUrl",
                ["FsMI_ThumbImgURL"] = "miThumbImgURL",
                ["FsMI_URL"] = "miUrl",
                ["FsMI_Key"] = "miKey",
                ["FsMI_GroupKey"] = "miGroupKey",
                ["FsMI_Size"] = "miSize",
                ["FsMI_Desc"] = "miDesc"
            };
            var data = sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                return value;
            });
            return data;
        }
        class mediaList
        {
            public int miId { get; set; }
            public int miIndex { get; set; }
            public int miType { get; set; }
            public string miTitle { get; set; }
            public string miUrl { get; set; }
            public string miSize { get; set; }
            public string miDuration { get; set; }
            public string miBase64 { get; set; }
            public string miImgUrl { get; set; }
            public string miDesc { get; set; }
        }
        #endregion
        /// <summary>
        /// 媒体头列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize(accessId = 403)]
        public JsonResult mediaTitle()
        {
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT id,text,url,groupKey,title,show,type,mianUrl,isMain FROM dbo.MediaInfoGroupKey";
            db.IsProc = false;
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_TomediaInfoTitle(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }
        /// <summary>
        /// 图片集/视频集媒体头
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize(accessId = 403)]
        public JsonResult mediaInfoTitle()
        {
            var type = Request.Form["type"].xTo<short>();
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT id,text,url,groupKey,title,show,type,isMain FROM dbo.MediaInfoGroupKey WHERE show=1 AND type=@type";
            db.IsProc = false;
            db.AddParameter("@type", SqlDbType.SmallInt, type);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_TomediaInfoTitle(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }
        /// <summary>
        /// 媒体头保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public JsonResult mediaTitleSave()
        {
            var optType = Request.Form["optType"].xTo<short>();
            var id = Request.Form["id"].xTo<int>();
            var text = Request.Form["text"].xTrim();
            var url = Request.Form["url"].xTrim();
            var mianUrl = Request.Form["mianUrl"].xTrim();
            var groupKey = Request.Form["groupKey"].xTrim();
            var title = Request.Form["title"].xTrim();
            var show = Request.Form["show"].xTo<short>();
            var type = Request.Form["type"].xTo<short>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_mediaTitleSave";
            db.IsProc = true;
            db.AddParameter("@optType", SqlDbType.SmallInt, optType);
            db.AddParameter("@id", SqlDbType.Int, id);
            db.AddParameter("@text", SqlDbType.NVarChar, text, 50);
            db.AddParameter("@url", SqlDbType.NVarChar, url, 128);
            db.AddParameter("@mianUrl", SqlDbType.NVarChar, mianUrl, 128);
            db.AddParameter("@groupKey", SqlDbType.VarChar, groupKey, 128);
            db.AddParameter("@title", SqlDbType.NVarChar, title, 50);
            db.AddParameter("@show", SqlDbType.SmallInt, show);
            db.AddParameter("@type", SqlDbType.SmallInt, type);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        /// <summary>
        /// 媒体保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public JsonResult mediaInfoSave()
        {
            var miGroupKey = Request.Form["miGroupKey"].xTrim();
            var mediaList = Request.Form["mediaList"].xTrim().xUrlDecode();
            string xml = null;
            if (mediaList.Length > 0)
            {
                XElement xel = null;
                try
                {
                    var json = mediaList.xConvertJsonToObject<List<mediaList>>();
                    xel = new XElement("xml");
                    foreach (var x in json)
                    {
                        xel.Add(new XElement("x"
                            , new XElement("miId", x.miId)
                            , new XElement("miType", x.miType)
                            , new XElement("miTitle", x.miTitle)
                            , new XElement("miUrl", x.miUrl)
                            , new XElement("miSize", x.miSize)
                            , new XElement("miDuration", x.miDuration)
                            , new XElement("miBase64", x.miBase64)
                            , new XElement("miImgUrl", x.miImgUrl)
                            , new XElement("miDesc", x.miDesc)
                        ));
                    }
                }
                catch
                {
                    return backJson(1, "参数解析异常.mediaList");
                }
                if (xel != null) xml = xel.ToString(SaveOptions.DisableFormatting);
            };
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MediaInfoSave";
            db.IsProc = true;
            db.AddParameter("@FsMI_GroupKey", SqlDbType.VarChar, miGroupKey, 128);
            db.AddParameter("@mediaList", SqlDbType.NVarChar, xml, -1);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult mediaInfoList()
        {
            var aResult = new ResultObj<object>();
            var list = new List<object>();
            var miGroupKey = Request.Form["miGroupKey"].xTrim();
            var pageIndex = Request.Form["pageIndex"].xTo<int>();//页码
            var pageSize = Request.Form["pageSize"].xTo<int>();//每页记录数
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MediaInfoList";
            db.IsProc = true;
            db.AddParameter("@FsMI_GroupKey", SqlDbType.VarChar, miGroupKey, 128);
            db.AddParameter("@PageIndex", System.Data.SqlDbType.Int, pageIndex, parameterDirection: System.Data.ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", System.Data.SqlDbType.Int, pageSize, parameterDirection: System.Data.ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", System.Data.SqlDbType.Int, 0, parameterDirection: System.Data.ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_TomediaList(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            aResult.PageSize = db.OutParameters["PageSize"].xTo<int>();
            aResult.PageIndex = db.OutParameters["PageIndex"].xTo<int>();
            aResult.RowCount = db.OutParameters["RowCount"].xTo<int>();
            return backJson(0, null, new
            {
                pageIndex = aResult.PageIndex,
                pageSize = aResult.PageSize,
                rowCount = aResult.RowCount,
                list = list
            });
        }
        [HttpPost]
        public JsonResult mediaInfoOne()
        {
            object data = null;
            var miGroupKey = Request.Form["miGroupKey"].xTrim();
            if (string.IsNullOrWhiteSpace(miGroupKey)) return backJson(1, "缺少【媒体组】参数");
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT TOP 1 * FROM dbo.MediaInfo WHERE FnMI_Type=4 AND FsMI_GroupKey=@FsMI_GroupKey ORDER BY NEWID();";
            db.IsProc = false;
            db.AddParameter("@FsMI_GroupKey", SqlDbType.VarChar, miGroupKey, 128);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = _TomediaList(sdr);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }

        [HttpPost]
        [v3Authorize(accessId = 404)]
        public JsonResult graphicImgSave()
        {
            var list = new List<object>();

            var title = Request.Form["title"].xTrim();
            var desc = Request.Form["desc"].xTrim();
            var optType = Request.Form["optType"].xTo<int>();//页码
            var id = Request.Form["id"].xTo<int>();//每页记录数
            var mediaList = Request.Form["mediaList"].xTrim().TrimStart(',').TrimEnd(',');
            XElement xml = new XElement("xml");
            if (mediaList.Length > 0)
            {
                foreach (var x in mediaList.Split(','))
                {
                    if (x.xTrim().Length > 0)
                    {
                        xml.Add(new XElement("x",
                                     new XElement("miUrl", x)
                                 )
                             );
                    }
                }
            };
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_graphicImgSave";
            db.IsProc = true;
            db.AddParameter("@mediaList", SqlDbType.NVarChar, xml.ToString(), -1);
            db.AddParameter("@title", System.Data.SqlDbType.NVarChar, title, 128);
            db.AddParameter("@desc", System.Data.SqlDbType.NVarChar, desc, 128);
            db.AddParameter("@optType", System.Data.SqlDbType.Int, optType);
            db.AddParameter("@id", System.Data.SqlDbType.Int, id);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_TographicImg(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }
        #endregion 图片集

        #region 机油信息

        Dictionary<string, object> _ToengineOil(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["eoId"] = "eoId",
                ["eoBrand"] = "eoBrand",
                ["eoModel"] = "eoModel",
                ["eoApplications"] = "eoApplications",
                ["eoCapacity"] = "eoCapacity",
                ["eoPrice"] = "eoPrice",
                ["eoStock"] = "eoStock",
                ["eoImg"] = "eoImg",
                ["eoOldProce"] = "eoOldProce",
                ["eoTime"] = "eoTime",
                ["eoAddTime"] = "eoAddTime",
                ["eoMid"] = "eoMid",
                ["eoOpenId"] = "eoOpenId",
                //车型大全
                ["cId"] = "cId",
                ["cName"] = "cName",
                //用户信息
                ["uiId"] = "uiId",
                ["root"] = "root",
                ["uiName"] = "uiName",
                ["pwd"] = "pwd",
                ["openId"] = "openId",
                ["session_key"] = "session_key",
                ["account"] = "account",
                ["uiTime"] = "uiTime",
                ["state"] = "state",
                ["uiMark"] = "uiMark",
                ["openkey"] = "openkey",
                //记账信息
                ["biId"] = "biId",
                ["uiName"] = "uiName",
                ["time"] = "time",
                ["payType"] = "payType",
                ["addTime"] = "addTime",
                ["biPrice"] = "biPrice",
                ["biCount"] = "biCount",
                ["biMark"] = "biMark",
                ["session_key"] = "session_key",
                ["account"] = "account",
                ["openId"] = "openId",
                ["biStatus"] = "biStatus",
                ["biProfit"] = "biProfit",
                ["biSum"] = "biSum",
                ["bioldSum"] = "bioldSum",
                ["upTime"] = "upTime",
                ["biOpenId"] = "biOpenId"
            };
            var data = sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                if (key == "time")
                {
                    return value.xFormatDateTime("yyyy-MM-dd");
                }
                if (key == "addTime" || key == "eoTime" || key == "upTime" || key == "eoAddTime" || key == "uiTime")
                {
                    return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                }
                if (key == "eoCapacity" || key == "eoOldProce" || key == "eoPrice" || key == "biPrice" || key == "biProfit" || key == "bioldSum"|| key == "biSum")
                {
                    return String.Format("{0:F2}", value);
                }
                return value;
            });
            data["optor"] = null;
            return data;
        }
        [HttpPost]
        [v3Authorize()]
        public ActionResult engineOilList()
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var eoApplications = Request.Form["eoApplications"].xTrim();
            var bId = Request.Form["bId"].xTo<int>();

            var list = new List<object>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_engineOilList";
            db.IsProc = true;
            db.AddParameter("@eoApplications", SqlDbType.VarChar, eoApplications, 64);
            db.AddParameter("@bId", SqlDbType.Int, bId);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToengineOil(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                list = list,
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
            });
        }
        [HttpGet]
        [v3Authorize()]
        public ActionResult engineOilListExport()
        {
            var pageIndex = Request.QueryString["pageIndex"].xTo<int>();
            var pageSize = Request.QueryString["pageSize"].xTo<int>();
            var eoApplications = Request.QueryString["eoApplications"].xTrim();
            var bId = Request.QueryString["bId"].xTo<int>();
            var isOld = Request.QueryString["isOld"].xTo<int>();

            var list = new List<Dictionary<string, object>>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_engineOilList";
            db.IsProc = true;
            db.AddParameter("@eoApplications", SqlDbType.VarChar, eoApplications, 64);
            db.AddParameter("@bId", SqlDbType.Int, bId);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToengineOil(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            var ExcelName = "机油列表" + System.DateTime.Now.xFormatDateTime("yyyy-MM-dd HH:mm:ss");

            Aspose.Cells.Workbook wk = GetengineOilList(list, isOld);
            return File(wk.SaveToStream().ToArray(), "application/x-xls", ExcelName.xUrlEncode() + ".xlsx");
        }
        internal Aspose.Cells.Workbook GetengineOilList(List<Dictionary<string, object>> crlist, int isOld)
        {
            Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();
            Aspose.Cells.Worksheet sheet = wk.Worksheets[0];

            #region  表头
            sheet.Cells[0, 0].PutValue("机油品牌");
            sheet.Cells[0, 1].PutValue("机油型号");
            sheet.Cells[0, 2].PutValue("容量（/L）");
            sheet.Cells[0, 3].PutValue("适用车型");
            sheet.Cells[0, 4].PutValue("售价（元）");
            sheet.Cells[0, 5].PutValue("库存");
            if (isOld > 0) { sheet.Cells[0, 6].PutValue("底价（元）"); };
            #endregion

            #region 表内容
            var row = 1;
            if (crlist.Count > 0)
            {
                foreach (var obj in crlist)
                {
                    sheet.Cells[row, 0].PutValue(obj["eoBrand"].xTrim());
                    sheet.Cells[row, 1].PutValue(obj["eoModel"].xTrim());
                    sheet.Cells[row, 2].PutValue(obj["eoCapacity"].xTrim());
                    sheet.Cells[row, 3].PutValue(obj["eoApplications"].xTrim());
                    sheet.Cells[row, 4].PutValue(obj["eoPrice"].xTrim());
                    sheet.Cells[row, 5].PutValue(obj["eoStock"].xTrim());
                    if (isOld > 0) { sheet.Cells[row, 6].PutValue(obj["eoOldProce"].xTrim()); };
                    row++;
                }
            }
            #endregion

            #region 样式
            var style = wk.CreateStyle();
            style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            style.SetBorder(Aspose.Cells.BorderType.LeftBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.SetBorder(Aspose.Cells.BorderType.RightBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.SetBorder(Aspose.Cells.BorderType.TopBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.SetBorder(Aspose.Cells.BorderType.BottomBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.IsTextWrapped = true;
            //sheet.AutoFitColumns();
            //sheet.AutoFitRows();
            sheet.Cells.CreateRange(0, 0, row, isOld > 0 ? 7 : 6).SetStyle(style);

            //表头加粗、居中
            //style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            style.Font.IsBold = true;
            style.Font.Color = System.Drawing.Color.White;//字体颜色
            style.Pattern = Aspose.Cells.BackgroundType.Solid;
            style.ForegroundColor = System.Drawing.Color.Teal;//背景色
            style.BackgroundColor = System.Drawing.Color.Teal;//背景色
            sheet.FreezePanes(1, 0, 1, 0);//固定表头
            sheet.Cells.CreateRange(0, 0, 1, isOld > 0 ? 7 : 6).SetStyle(style);

            //考试名称列
            //sheet.Cells.CreateRange(1, 1, row, 1).ColumnWidth = 24;
            //style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Left;
            //style.Font.IsBold = false;
            //sheet.Cells.CreateRange(1, 1, row - 1, 1).SetStyle(style);
            sheet.Cells.CreateRange(0, 0, row, isOld > 0 ? 7 : 6).RowHeight = 25;
            //其它列宽
            sheet.Cells.CreateRange(0, 0, row, 1).ColumnWidth = 20;
            sheet.Cells.CreateRange(0, 1, row, 1).ColumnWidth = 40;
            sheet.Cells.CreateRange(0, 2, row, 1).ColumnWidth = 20;
            sheet.Cells.CreateRange(0, 3, row, 1).ColumnWidth = 40;
            sheet.Cells.CreateRange(0, 4, row, isOld > 0 ? 3 : 2).ColumnWidth = 20;
            #endregion

            return wk;
        }

        [HttpPost]
        [v3Authorize()]
        public ActionResult engineOilAdd()
        {
            var optType = Request.Form["optType"].xTo<int>();
            var eoId = Request.Form["eoId"].xTo<int>();
            var eoBrand = Request.Form["eoBrand"].xTrim();
            var eoModel = Request.Form["eoModel"].xTrim();
            var eoApplications = Request.Form["eoApplications"].xTrim();
            var eoCapacity = Request.Form["eoCapacity"].xTo<double>();
            var eoPrice = Request.Form["eoPrice"].xTo<double>();
            var eoOldProce = Request.Form["eoOldProce"].xTo<double>();
            var eoStock = Request.Form["eoStock"].xTo<short>();
            var eoImg = Request.Form["eoImg"].xTrim();
            var openId = Request.Form["openId"].xTrim();
            var state = Request.Form["state"].xTrim();

            object data = null;
            string xml = null;
            XElement xmlObj = new XElement("xml");
            if (eoApplications.Length > 0)
            {
                try
                {
                    foreach (var x in eoApplications.Split('、'))
                    {
                        if (x.xTrim().Length > 0)
                        {
                            xmlObj.Add(new XElement("x",
                                         new XElement("name", x)
                                     )
                            );
                        }
                    };
                }
                catch (Exception ex)
                {
                    return backJson(1, "xml解析错误" + ex.Message);
                };
            };
            if (xmlObj != null) xml = xmlObj.ToString(SaveOptions.DisableFormatting);

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_engineOilSave";
            db.IsProc = true;
            db.AddParameter("@optType", SqlDbType.Int, optType);
            db.AddParameter("@eoId", SqlDbType.Int, eoId);
            db.AddParameter("@eoBrand", SqlDbType.NVarChar, eoBrand, 50);
            db.AddParameter("@eoModel", SqlDbType.NVarChar, eoModel, 50);
            db.AddParameter("@eoApplications", SqlDbType.NVarChar, eoApplications, 50);
            db.AddParameter("@eoCapacity", SqlDbType.Decimal, eoCapacity);
            db.AddParameter("@eoPrice", SqlDbType.Decimal, eoPrice);
            db.AddParameter("@eoOldProce", SqlDbType.Decimal, eoOldProce);
            db.AddParameter("@eoStock", SqlDbType.SmallInt, eoStock);
            db.AddParameter("@eoImg", SqlDbType.NVarChar, eoImg, -1);
            db.AddParameter("@openId", SqlDbType.NVarChar, openId, 50);
            db.AddParameter("@state", SqlDbType.NVarChar, state, 50);
            db.AddParameter("@xml", SqlDbType.NVarChar, xml, -1);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = _ToengineOil(sdr);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }
        #endregion 机油信息

        #region 车型大全
        [HttpPost]
        [v3Authorize()]
        public ActionResult getCars()
        {

            var list = new List<object>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT cId,cName FROM dbo.eoCar";
            db.IsProc = false;
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToengineOil(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }
        #endregion 车型大全

        #region 记账
        Dictionary<string, object> _ToeoModel(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["bId"] = "value",
                ["bName"] = "text",
                ["children"] = "children"

            };
            return sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                if (key == "children")
                {
                    return value.xTrim().xConvertJsonToObject<List<eoModel>>();
                }
                return value;
            });
        }
        class eoModel
        {
            public string value { get; set; }
            public string text { get; set; }
            public Boolean disable { get; set; }
            public int eoStock { get; set; }
            public decimal eoPrice { get; set; }
            public string eoBrand { get; set; }
        }
        /// <summary>
        /// 获取机油列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult eoModelList()
        {
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_eoModelList";
            db.IsProc = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToeoModel(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }
        /// <summary>
        /// 账单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult enBillList()
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var eoApplications = Request.Form["eoApplications"].xTrim();
            var bId = Request.Form["bId"].xTo<int>();
            var beginTime = Request.Form["beginTime"].xTrim().xToDatetime("yyyy-MM-dd");
            var endTime = Request.Form["endTime"].xTrim().xToDatetime("yyyy-MM-dd");
            var list = new List<object>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_eoBillList";
            db.IsProc = true;
            db.AddParameter("@beginTime", SqlDbType.Date, beginTime);
            db.AddParameter("@endTime", SqlDbType.Date, endTime);
            db.AddParameter("@eoApplications", SqlDbType.VarChar, eoApplications, 64);
            db.AddParameter("@bId", SqlDbType.Int, bId);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@Sum", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@Count", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@Profit", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@XJ", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@WX", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@ZFB", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToengineOil(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                list = list,
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
                Sum = db.OutParameters["Sum"].xTrim(),
                Count = db.OutParameters["Count"].xTo<int>(),
                Profit = db.OutParameters["Profit"].xTrim(),
                XJ = db.OutParameters["XJ"].xTrim(),
                WX = db.OutParameters["WX"].xTrim(),
                ZFB = db.OutParameters["ZFB"].xTrim(),
            });
        }
        [HttpPost]
        [v3Authorize()]
        public ActionResult enBillObj()
        {
            var biId = Request.Form["biId"].xTo<int>();

            object data = null;

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_eoBillObj";
            db.IsProc = true;
            db.AddParameter("@biId", SqlDbType.Int, biId);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = _ToengineOil(sdr);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }
        Dictionary<string, object> _ToeoBill(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {
                ["biId"] = "biId",
                ["eoId"] = "eoId",
                ["time"] = "time",
                ["addTime"] = "addTime",
                ["biPrice"] = "biPrice",
                ["biCount"] = "biCount",
                ["biSum"] = "biSum",
                ["biMark"] = "biMark",
                ["oiplatform"] = "oiplatform",
                ["oibrand"] = "oibrand",
                ["oimodel"] = "oimodel",
                ["biStatus"] = "biStatus"
            };
            return sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                if (key == "time")
                {
                    return value.xFormatDateTime("yyyy-MM-dd");
                }
                if (key == "children")
                {
                    return value.xTrim().xConvertJsonToObject<List<eoModel>>();
                }
                return value;
            });
        }
        /// <summary>
        /// 记账
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult eoBillAdd()
        {
            var optType = Request.Form["optType"].xTo<int>();
            var biId = Request.Form["biId"].xTo<int>();
            var mId = Request.Form["mId"].xTo<short>();
            var payType = Request.Form["payType"].xTo<short>();
            var time = Request.Form["currentDay"].xTrim().xToDatetime("yyyy-MM-dd");
            var biPrice = Request.Form["biPrice"].xTo<double>();
            var count = Request.Form["count"].xTo<short>();
            var biMark = Request.Form["biMark"].xTrim();
            var openId = Request.Form["openId"].xTrim();
            var state = Request.Form["state"].xTrim();

            object data = null;
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_eoBillSave";
            db.IsProc = true;
            db.AddParameter("@optType", SqlDbType.Int, optType);
            db.AddParameter("@biId", SqlDbType.Int, biId);
            db.AddParameter("@mId", SqlDbType.SmallInt, mId);
            db.AddParameter("@payType", SqlDbType.SmallInt, payType);
            db.AddParameter("@time", SqlDbType.Date, time);
            db.AddParameter("@biPrice", SqlDbType.Decimal, biPrice);
            db.AddParameter("@count", SqlDbType.SmallInt, count);
            db.AddParameter("@biMark", SqlDbType.NVarChar, biMark, -1);
            db.AddParameter("@openId", SqlDbType.NVarChar, openId, 50);
            db.AddParameter("@state", SqlDbType.NVarChar, state, 50);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = _ToeoBill(sdr);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }
        /// <summary>
        /// 导出账单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [v3Authorize()]
        public ActionResult billListExport()
        {
            var pageIndex = Request.QueryString["pageIndex"].xTo<int>();
            var pageSize = Request.QueryString["pageSize"].xTo<int>();
            var eoApplications = Request.QueryString["eoApplications"].xTrim();
            var bId = Request.QueryString["bId"].xTo<int>();
            var beginTime = Request.QueryString["beginTime"].xTrim().xToDatetime("yyyy-MM-dd");
            var endTime = Request.QueryString["endTime"].xTrim().xToDatetime("yyyy-MM-dd");
            var list = new List<Dictionary<string, object>>();
            Dictionary<string, object> data = new Dictionary<string, object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_eoBillList";
            db.IsProc = true;
            db.AddParameter("@beginTime", SqlDbType.Date, beginTime);
            db.AddParameter("@endTime", SqlDbType.Date, endTime);
            db.AddParameter("@eoApplications", SqlDbType.VarChar, eoApplications, 64);
            db.AddParameter("@bId", SqlDbType.Int, bId);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@Sum", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@Count", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@Profit", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@XJ", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@WX", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@ZFB", SqlDbType.Decimal, 0, Scale: 2, parameterDirection: ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToengineOil(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            var ExcelName = "账单" + System.DateTime.Now.xFormatDateTime("yyyy-MM-dd HH:mm:ss");

            Aspose.Cells.Workbook wk = GetTeacherExam(list, db.OutParameters["Sum"].xTrim(), db.OutParameters["Count"].xTo<int>(), db.OutParameters["Profit"].xTrim(), db.OutParameters["XJ"].xTrim(), db.OutParameters["WX"].xTrim(), db.OutParameters["ZFB"].xTrim());
            return File(wk.SaveToStream().ToArray(), "application/x-xls", ExcelName.xUrlEncode() + ".xlsx");
        }
        internal Aspose.Cells.Workbook GetTeacherExam(List<Dictionary<string, object>> crlist, string sum, int count, string profit, string xj, string wx, string zfb)
        {
            Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();
            Aspose.Cells.Worksheet sheet = wk.Worksheets[0];

            #region  表头
            sheet.Cells[0, 0].PutValue("售出时间");
            sheet.Cells[0, 1].PutValue("机油品牌/型号");
            sheet.Cells[0, 2].PutValue("适用车型");
            sheet.Cells[0, 3].PutValue("售价（元）");
            sheet.Cells[0, 4].PutValue("支付方式");
            sheet.Cells[0, 5].PutValue("底价（元）");
            sheet.Cells[0, 6].PutValue("销售数量");
            sheet.Cells[0, 7].PutValue("总利润（元）");
            sheet.Cells[0, 8].PutValue("备注");
            #endregion

            #region 表内容
            var row = 1;
            if (crlist.Count > 0)
            {
                foreach (var obj in crlist)
                {
                    var payType = obj["payType"].xTo<int>();
                    sheet.Cells[row, 0].PutValue(obj["time"].xTrim());
                    sheet.Cells[row, 1].PutValue(obj["eoBrand"].xTrim() + '/' + obj["eoModel"].xTrim());
                    sheet.Cells[row, 2].PutValue(obj["eoApplications"].xTrim());
                    sheet.Cells[row, 3].PutValue(obj["biPrice"].xTrim());
                    sheet.Cells[row, 4].PutValue(payType == 0 ? "现金" : payType == 1 ? "微信" : payType == 2 ? "支付宝" : "");
                    sheet.Cells[row, 5].PutValue(obj["eoOldProce"].xTrim());
                    sheet.Cells[row, 6].PutValue(obj["biCount"].xTrim());
                    sheet.Cells[row, 7].PutValue(obj["biProfit"].xTrim());
                    sheet.Cells[row, 8].PutValue(obj["biMark"].xTrim());
                    row++;
                }
            }
            sheet.Cells[row + 1, 0].PutValue("合计");
            sheet.Cells[row + 1, 1].PutValue("销售额：" + sum + "元");
            sheet.Cells[row + 1, 2].PutValue("现金：" + sum + "元");
            sheet.Cells[row + 1, 3].PutValue("微信：" + sum + "元");
            sheet.Cells[row + 1, 4].PutValue("支付宝：" + sum + "元");
            sheet.Cells[row + 1, 5].PutValue("总利润" + sum + "元");
            sheet.Cells[row + 1, 6].PutValue("");
            sheet.Cells[row + 1, 7].PutValue("");
            sheet.Cells[row + 1, 8].PutValue("");
            #endregion

            #region 样式
            var style = wk.CreateStyle();
            style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            style.SetBorder(Aspose.Cells.BorderType.LeftBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.SetBorder(Aspose.Cells.BorderType.RightBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.SetBorder(Aspose.Cells.BorderType.TopBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.SetBorder(Aspose.Cells.BorderType.BottomBorder, Aspose.Cells.CellBorderType.Thin, System.Drawing.Color.Gray);
            style.IsTextWrapped = true;
            //sheet.AutoFitColumns();
            sheet.AutoFitRows();
            sheet.Cells.CreateRange(0, 0, row, 9).SetStyle(style);

            //表头加粗、居中
            //style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            style.Font.IsBold = true;
            style.Font.Color = System.Drawing.Color.White;//字体颜色
            style.Pattern = Aspose.Cells.BackgroundType.Solid;
            style.ForegroundColor = System.Drawing.Color.Teal;//背景色
            style.BackgroundColor = System.Drawing.Color.Teal;//背景色
            sheet.FreezePanes(1, 0, 1, 0);//固定表头
            sheet.Cells.CreateRange(0, 0, 1, 9).SetStyle(style);

            //考试名称列
            //sheet.Cells.CreateRange(1, 1, row, 1).ColumnWidth = 24;
            //style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Left;
            //style.Font.IsBold = false;
            //sheet.Cells.CreateRange(1, 1, row - 1, 1).SetStyle(style);
            var styleRed = wk.CreateStyle();
            styleRed.Font.Color = System.Drawing.Color.Red;
            var styleGreen = wk.CreateStyle();
            styleGreen.Font.Color = System.Drawing.Color.Green;
            foreach (var obj in crlist)
            {
                var payType = obj["biProfit"].xTo<double>();
                if (payType < 0)
                {
                    sheet.Cells[row, 7].SetStyle(styleRed);
                }
                else
                {
                    sheet.Cells[row, 7].SetStyle(styleGreen);
                }
                row++;
            }
            //其它列宽
            sheet.Cells.CreateRange(0, 0, row, 1).ColumnWidth = 20;
            sheet.Cells.CreateRange(0, 1, row, 2).ColumnWidth = 40;
            sheet.Cells.CreateRange(0, 3, row, 5).ColumnWidth = 20;
            sheet.Cells.CreateRange(0, 8, row, 1).ColumnWidth = 80;
            #endregion

            return wk;
        }

        #endregion 记账

        #region 菜单 权限
        #region 字典
        static Dictionary<string, object> _Tofun(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {
                ["FnPR_ID"] = "rdId",
                ["FnFL_ID"] = "Id",
                ["FnFL_SuperiorID"] = "flpId",
                ["FnFL_Level"] = "level",
                ["FsFL_Name"] = "name",
                ["state"] = "state",
                ["url"] = "url",
                ["color"] = "color",
                ["icon"] = "icon",
                ["show"] = "show"
            };
            var data = sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                return value;
            });

            return data;
        }
        //获取用户信息
        public static ResultObj<YYSService.unifiedUser> getUserInfo(string openId)
        {
            var data = new ResultObj<YYSService.unifiedUser>();
            if (openId == null) return data.SetError("会话已超时.exp");
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_getCurrentUser";
            db.IsProc = true;
            db.AddParameter("@openId", System.Data.SqlDbType.NVarChar, openId, -1);
            db.AddParameter("@source", System.Data.SqlDbType.Int, 3);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data.Obj = sdr.xTo<YYSService.unifiedUser>();
            };
            db.Exec();
            if (db.HasError) return data.SetError(db.Error);
            return data;
        }
        static Dictionary<string, object> _ToOptorInfo(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {
                ["uiName"] = "uiName",
                ["openId"] = "openId",
                ["possess"] = "possess"
            };
            return sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                return value;
            });
        }
        class menu
        {
            public int badge { get; set; }
            public string name { get; set; }
            public string state { get; set; }
            public string url { get; set; }
            public string color { get; set; }
            public string icon { get; set; }
            public Boolean show { get; set; }
            public Boolean pcShow { get; set; }
        }
        #endregion
        [HttpPost]
        [v3Authorize(accessId = 999)]
        public ActionResult GetFfun()
        {
            var openId = Request.Form["openId"].xTrim();
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT FnPR_ID,FnFL_ID,FnFL_SuperiorID,FnFL_Level,FnFL_SubordinateNum,FsFL_Name,FsFL_UseType,state,url,color,icon,show FROM dbo.FunctionList";
            db.IsProc = false;
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_Tofun(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            var data = getUserInfo(openId);
            if (data.HasError) return backJson(1, data.Error, data);
            return backJson(0, null, new
            {
                list = list,
                data = data.Obj
            });
        }
        /// <summary>
        /// 用户权限保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult funSave()
        {
            var openId = Request.Form["openId"].xTrim();
            var idList = Request.Form["idList"].xTrim().TrimStart(',').TrimEnd(',');
            XElement xmlObj = new XElement("xml");
            if (idList.Length > 0)
            {
                foreach (var x in idList.Split(','))
                {
                    if (x.xTrim().Length > 0)
                    {
                        xmlObj.Add(new XElement("x",
                                     new XElement("id", x)
                                 )
                             );
                    }
                }
            }
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_funSave";
            db.IsProc = true;
            db.AddParameter("@openId", SqlDbType.NVarChar, openId, 50);
            db.AddParameter("@xml", SqlDbType.NVarChar, xmlObj.ToString(), -1);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        /// <summary>
        /// 权限保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult menuSave()
        {
            var optType = Request.Form["optType"].xTo<int>();
            var hdPid = Request.Form["hdPid"].xTo<int>();
            var hdId = Request.Form["hdId"].xTo<int>();
            var level = Request.Form["level"].xTo<int>();
            var hdTitle = Request.Form["hdTitle"].xTrim();
            var state = Request.Form["state"].xTrim();
            var url = Request.Form["url"].xTrim();
            var color = Request.Form["color"].xTrim();
            var icon = Request.Form["icon"].xTrim();
            var show = Request.Form["showType"].xTo<int>();
            if (!optType.xRange<int>(0, 1, 2)) return backJson(1, "无效参数");
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MenuSave";
            db.IsProc = true;
            db.AddParameter("@optType", SqlDbType.Int, optType);
            db.AddParameter("@FnFL_ID", SqlDbType.Int, hdId);
            db.AddParameter("@FnFL_SuperiorID", SqlDbType.Int, hdPid);
            db.AddParameter("@FnFL_Level", SqlDbType.Int, level);
            db.AddParameter("@FsFL_Name", SqlDbType.VarChar, hdTitle, 50);
            db.AddParameter("@FsFL_UseType", SqlDbType.VarChar, "|3|", 32);
            db.AddParameter("@state", SqlDbType.VarChar, state, 50);
            db.AddParameter("@url", SqlDbType.VarChar, url, 50);
            db.AddParameter("@color", SqlDbType.VarChar, color, 50);
            db.AddParameter("@icon", SqlDbType.VarChar, icon, 50);
            db.AddParameter("@show", SqlDbType.Int, show);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }

        /// <summary>
        /// 获取所有用户某个权限是否开通
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public JsonResult optorList()
        {
            var elId = Request.Form["elId"].xTo<int>();
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT openId,uiName,openId_R,root, possess= (SELECT 1 FROM FunctionDefine T2  WHERE T1.openId=T2.FnOI_ID AND FnFL_ID=@elId) FROM dbo.userInfo T1 ORDER BY uiId";
            db.IsProc = false;
            db.AddParameter("@elId", SqlDbType.Int, elId);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToOptorInfo(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }
        /// <summary>
        /// 批量给权限设置人
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult userfunSave()
        {
            var id = Request.Form["id"].xTrim();
            var idList = Request.Form["idList"].xTrim().TrimStart(',').TrimEnd(',');
            XElement xmlObj = new XElement("xml");
            if (idList.Length > 0)
            {
                foreach (var x in idList.Split(','))
                {
                    if (x.xTrim().Length > 0)
                    {
                        xmlObj.Add(new XElement("x",
                                     new XElement("id", x)
                                 )
                             );
                    }
                }
            }
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_userfunSave";
            db.IsProc = true;
            db.AddParameter("@elId", SqlDbType.BigInt, id, 50);
            db.AddParameter("@xml", SqlDbType.NVarChar, xmlObj.ToString(), -1);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        #endregion

        #region 用户
        /// <summary>
        /// 修改用户资料
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult getUserInfo()
        {
            var optType = Request.Form["optType"].xTo<short>(4);
            var uiId = Request.Form["uiId"].xTo<int>();
            var root = Request.Form["root"].xTo<int>();
            var uiName = Request.Form["uiName"].xTrim();
            var account = Request.Form["account"].xTrim();
            var uId = Request.Form["uId"].xTrim();
            var openId = Request.Form["openId"].xTrim();
            var cpu_id = Request.Form["cpu_id"].xTrim();
            var uiMark = Request.Form["uiMark"].xTrim();
            var state = Request.Form["state"].xTrim();
            var imgUrl = Request.Form["imgUrl"].xTrim();
            var bucketName = Request.Form["bucketName"].xTrim();
            var email = Request.Form["email"].xTrim();
            string xml = null;
            XElement xmlObj = new XElement("xml");
            var optor = Request.v3UnifiedUser();
            if (state.Length > 0)
            {
                try
                {
                    foreach (var x in state.Split(','))
                    {
                        if (x.xTrim().Length > 0)
                        {
                            xmlObj.Add(new XElement("x",
                                         new XElement("name", x)
                                     )
                            );
                        }
                    };
                }
                catch (Exception ex)
                {
                    return backJson(1, "xml解析错误" + ex.Message);
                };
            };
            if (xmlObj != null) xml = xmlObj.ToString(SaveOptions.DisableFormatting);
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_userInfoSave";
            db.IsProc = true;
            db.AddParameter("@optType", SqlDbType.Int, optType);
            db.AddParameter("@uiId", SqlDbType.Int, uiId);
            db.AddParameter("@fId", SqlDbType.VarChar, "", 50);
            db.AddParameter("@account", SqlDbType.VarChar, account, 50);
            db.AddParameter("@uId", SqlDbType.VarChar, uId, 50);
            db.AddParameter("@cpu_id", SqlDbType.NVarChar, cpu_id, 256);
            db.AddParameter("@state", SqlDbType.NVarChar, state, 50);
            db.AddParameter("@root", SqlDbType.Int, root);
            db.AddParameter("@uiName", SqlDbType.NVarChar, uiName, 50);
            db.AddParameter("@openId", SqlDbType.NVarChar, openId, 50);
            db.AddParameter("@session_key", SqlDbType.NVarChar, "", 50);
            db.AddParameter("@uiMark", SqlDbType.NVarChar, uiMark, -1);
            db.AddParameter("@oiId", SqlDbType.NVarChar, optor.openId, 50);
            db.AddParameter("@xml", SqlDbType.NVarChar, xml, -1);
            db.AddParameter("@imgUrl", SqlDbType.NVarChar, imgUrl, 128);
            db.AddParameter("@bucketName", SqlDbType.VarChar, bucketName, 32);
            db.AddParameter("@email", SqlDbType.VarChar, email, 50);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public JsonResult userList()
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var sort = Request.Form["sort"].xTo<int>(0);
            var list = new List<object>();
            var optor = Request.v3UnifiedUser();
            if (optor.appId == 1)
            {
                sort = 1;
            }
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_userList";
            db.IsProc = true;
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.AddParameter("@sort", SqlDbType.Int, sort);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(sdr.xTo<YYSService.unifiedUser>());
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                list = list,
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
                optor = optor
            });
        }
        /// <summary>
        /// 用户关联
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [v3Authorize()]
        public ActionResult userRelationSave()
        {
            var optType = Request.Form["optType"].xTo<short>(0);
            var openId_R = Request.Form["openId_R"].xTrim();
            var optor = Request.v3UnifiedUser();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_userRelationSave";
            db.IsProc = true;
            db.AddParameter("@optType", SqlDbType.Int, optType);
            db.AddParameter("@openId", SqlDbType.NVarChar, optor.openId, 50);
            db.AddParameter("@openId_R", SqlDbType.NVarChar, openId_R, 50);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        #endregion 用户

        #region 富文本
        [HttpPost]
        [v3Authorize()]
        public JsonResult wangEditorSave()
        {
            var optType = Request.Form["optType"].xTo<int>();
            var id = Request.Form["id"].xTo<int>();
            var title = Request.Form["title"].xTrim();
            var content = Request.Form["content"].xTrim().xUrlDecode();
            var openId = Request.Form["openId"].xTrim();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_wangEditorSave";
            db.IsProc = true;
            db.AddParameter("@id", SqlDbType.Int, id);
            db.AddParameter("@optType", SqlDbType.Int, optType);
            db.AddParameter("@title", SqlDbType.VarChar, title, 50);
            db.AddParameter("@html", SqlDbType.NVarChar, content, -1);
            db.AddParameter("@openId", SqlDbType.VarChar, openId, 50);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, content);
        }
        [HttpGet]
        [CompressHtml]
        public ActionResult wangEditorShare()
        {
            return View("~/Views/pc/helper/wangeditor.cshtml");
        }
        static Dictionary<string, object> _TowangEditor(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["id"] = "id",
                ["title"] = "title",
                ["html"] = "html",
                ["status"] = "status",
                ["openId"] = "openId",

            };
            return sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                if (key == "time")
                {
                    return value.xFormatDateTime("yyyy-MM-dd");
                }
                if (key == "addTime" || key == "eoTime" || key == "upTime" || key == "eoAddTime" || key == "uiTime")
                {
                    return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                }
                if (key == "eoCapacity" || key == "eoOldProce" || key == "eoPrice" || key == "biPrice" || key == "biProfit" || key == "bioldSum" || key == "biSum")
                {
                    return String.Format("{0:F2}", value);
                }
                return value;
            });
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult wangEditorList()
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_wangEditorList";
            db.IsProc = true;
            //db.AddParameter("@openId", SqlDbType.VarChar, openId, 50);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_TowangEditor(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                list = list,
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
            });
        }
        public static ResultObj<Dictionary<string, object>> _wangEditorInfo(int id)
        {
            var data = new ResultObj<Dictionary<string, object>>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT * FROM dbo.wangEditor WHERE id=@id";
            db.IsProc = false;
            db.AddParameter("@id", System.Data.SqlDbType.Int, id);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data.Obj = _TowangEditor(sdr);
            };
            db.Exec();
            if (db.HasError) return data.SetError(db.Error);
            return data;
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult wangEditorInfo()
        {
            var id = Request.Form["id"].xTo<int>();
            var docObj = _wangEditorInfo(id);
            if (docObj.HasError) backJson(1, docObj.Error);
            return backJson(0, "", docObj.Obj);
        }
        #endregion 富文本

        #region 公告
        [HttpPost]
        [v3Authorize()]
        public JsonResult noticeSave()
        {
            var optType = Request.Form["optType"].xTo<int>();
            var id = Request.Form["id"].xTo<int>();
            var scrollable = Request.Form["scrollable"].xTo<int>();
            var speed = Request.Form["speed"].xTo<int>(60);
            var closeable = Request.Form["closeable"].xTo<int>();
            var title = Request.Form["title"].xTrim();
            var msg = Request.Form["msg"].xTrim();
            var msg_key = Request.Form["editorId"].xTrim();
            var beginTime = Request.Form["beginTime"].xToDatetime("yyyy-MM-dd HH:mm:ss");
            var endTime = Request.Form["endTime"].xToDatetime("yyyy-MM-dd HH:mm:ss");
            var openId = Request.Form["openId"].xTrim();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.Exec, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_noticeSave";
            db.IsProc = true;
            db.AddParameter("@id", SqlDbType.Int, id);
            db.AddParameter("@optType", SqlDbType.Int, optType);
            db.AddParameter("@scrollable", SqlDbType.Int, scrollable);
            db.AddParameter("@closeable", SqlDbType.Int, closeable);
            db.AddParameter("@speed", SqlDbType.Int, speed);
            db.AddParameter("@title", SqlDbType.VarChar, title, 50);
            db.AddParameter("@msg", SqlDbType.NVarChar, msg, -1);
            db.AddParameter("@msg_key", SqlDbType.NVarChar, msg_key, 256);
            db.AddParameter("@beginTime", SqlDbType.DateTime, beginTime);
            db.AddParameter("@endTime", SqlDbType.DateTime, endTime);
            db.AddParameter("@openId", SqlDbType.VarChar, openId, 50);
            db.NeedOutError = true;
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null);
        }
        Dictionary<string, object> _Tonotice(System.Data.SqlClient.SqlDataReader sdr)
        {
            var dic = new Dictionary<string, string>()
            {

                ["id"] = "id",
                ["title"] = "title",
                ["msg_key"] = "msg_key",
                ["msg"] = "msg",
                ["beginTime"] = "beginTime",
                ["endTime"] = "endTime",
                ["time"] = "time",
                ["status"] = "status",
                ["openId"] = "openId",
                ["scrollable"] = "scrollable",
                ["closeable"] = "closeable",
                ["speed"] = "speed",

            };
            return sdr.xToDictionary(dic, exclude: null, formater: (key, value, _this) =>
            {
                if (key == "time" || key == "endTime" || key == "beginTime")
                {
                    return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                };
                return value;
            });
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult noticeList()
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var optor = Request.v3UnifiedUser();
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_noticeList";
            db.IsProc = true;
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_Tonotice(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                list = list,
                optor = optor,
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
            });
        }
        #endregion 公告

        #region 帮助文档
        /// <summary>
        /// 系统使用说明列表
        /// </summary>
        /// <returns></returns> 

        static Dictionary<string, object> _ToHelperDoc(System.Data.SqlClient.SqlDataReader sdr)
        {
            var _helperDoc = new Dictionary<string, string>()
            {
                { "FnHD_ID","hdId" } ,{ "FnHD_PID","hdPid" }
                ,{ "FnHD_Type","hdType" } ,{ "FsHD_Title","hdTitle" },{ "FsMI_Key","miKey" } ,{ "FdHD_MakeTime","makeTime" }
                ,{ "FdHD_CreateTime","creteTime" } ,{ "FnHD_Status","hdStatus" } ,{ "FnOI_ID","oiId"},{ "FsOI_Name","oiName" },{ "MediaList","mediaList" },{"share","share"},{"FsMI_Url","miUrl"}
            };

            return sdr.xToDictionary(_helperDoc, null, formater: (key, value, _this) =>
            {
                if (key == "FdHD_CreateTime" || key == "FdHD_MakeTime")
                {
                    return value.xFormatDateTime("yyyy-MM-dd HH:mm:ss");
                }
                if (key == "MediaList")
                {
                    if (value.xTrim().xIsNullOrEmpty()) return new object[] { };
                    System.Xml.Linq.XElement xel;
                    try
                    {
                        xel = value.xTrim().ConvertToXElement();
                    }
                    catch
                    {
                        return new object[] { };
                    }

                    return xel.Elements().Select(x => new mediaList
                    {
                        miId = x.xXmlValue<int>("FnMI_ID"),
                        miIndex = x.xXmlValue<int>("FnMI_Index"),
                        miType = x.xXmlValue<int>("FnMI_Type"),
                        miSize = x.xXmlValue<string>("FsMI_Size"),
                        miDuration = x.xXmlValue<string>("FsMI_Duration"),
                        miTitle = x.xXmlValue<string>("FsMI_Title"),
                        miUrl = x.xXmlValue<string>("FsMI_Url")
                    });
                }
                return value;
            });
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult HelperDocList()
        {
            var optor = Request.v3UnifiedUser();
            var max = optor.cando(30902) ? 1 : 0;
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "SELECT FnHD_ID, FnHD_PID ,FnHD_Type, FsHD_Title, FdHD_CreateTime, FnHD_Status, FsMI_Key, FnOI_ID, FsOI_Name, FdHD_MakeTime,share FROM dbo.TA_O_HelperDoc WHERE share=0 OR (share=1 AND FnOI_ID=@oiId) OR @max=1";
            db.AddParameter("@oiId", SqlDbType.NVarChar, optor.openId, 50);
            db.AddParameter("@max", SqlDbType.Int, max);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                var obj = _ToHelperDoc(sdr);
                list.Add(obj);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, list);
        }

        public static ResultObj<Dictionary<string, object>> _HelperDocInfo(string miKey, long id)
        {
            var data = new ResultObj<Dictionary<string, object>>();
            if (miKey.Length <= 0 && id <= 0) return data.SetError("无效参数");
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_HelperInfo";
            db.IsProc = true;
            db.AddParameter("@miKey", System.Data.SqlDbType.VarChar, miKey, 64);
            db.AddParameter("@id", System.Data.SqlDbType.BigInt, id);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data.Obj = _ToHelperDoc(sdr);
            };
            db.Exec();
            if (db.HasError) return data.SetError(db.HasSystemError ? "服务器内部错误.DB" : db.Error);
            return data;
        }

        [HttpPost]
        [v3Authorize()]
        public JsonResult HelperDocInfo()
        {
            var miKey = Request.Form["miKey"].xTrim();
            var id = Request.Form["hdId"].xTo<long>();
            var data = _HelperDocInfo(miKey, id);

            if (data.HasError) return backJson(1, data.Error);
            return backJson(0, null, data.Obj);
        }

        [HttpPost]
        [v3Authorize(accessId = 30901)]
        public JsonResult HelperDocSave()
        {
            var optType = Request.Form["optType"].xTo<int>(-1); //0：新增；1：修改；2：删除  3.启用/停用        
            var hdId = Request.Form["hdId"].xTo<int>(-1);
            var hdPid = Request.Form["hdPid"].xTo<int>(-1);
            var share = Request.Form["share"].xTo<int>(0);
            var hdType = Request.Form["hdType"].xTo<int>(-1);
            var hdTitle = Request.Form["hdTitle"].xTrim();
            var hdStatus = Request.Form["hdStatus"].xTo<int>();
            var mediaList = Request.Form["mediaList"].xTrim().xUrlDecode();

            if (!optType.xRange(0, 1, 2, 3)) return backJson(1, "无效参数.optType");
            if (optType > 0 && hdId == -1) return backJson(1, "无效参数.hdId");
            if (optType < 2)
            {
                if (hdPid < 0) return backJson(1, "无效参数.hdPid");
                if (hdType < 0) return backJson(1, "无效参数.hdType");
                if (hdTitle.Length == 0) return backJson(1, "无效参数.hdTitle");
            };
            string xml = null;
            if (mediaList.Length > 0)
            {
                XElement xel = null;
                try
                {
                    var json = mediaList.xConvertJsonToObject<List<mediaList>>();
                    xel = new XElement("xml");
                    foreach (var x in json)
                    {
                        xel.Add(new XElement("x"
                            , new XElement("miId", x.miId)
                            , new XElement("miIndex", x.miIndex)
                            , new XElement("miType", x.miType)
                            , new XElement("miTitle", x.miTitle)
                            , new XElement("miUrl", x.miUrl)
                            , new XElement("miSize", x.miSize)
                            , new XElement("miDuration", x.miDuration)
                        ));
                    }
                }
                catch
                {
                    return backJson(1, "参数解析异常.mediaList");
                }
                if (xel != null) xml = xel.ToString(SaveOptions.DisableFormatting);
            };
            var list = new List<object>();
            var optor = Request.v3UnifiedUser();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_HelperDocSave";
            db.IsProc = true;
            db.AddParameter("@optType", System.Data.SqlDbType.Int, optType);
            db.AddParameter("@FnHD_ID", System.Data.SqlDbType.BigInt, hdId);
            db.AddParameter("@share", System.Data.SqlDbType.Int, share);
            db.AddParameter("@FnHD_PID", System.Data.SqlDbType.BigInt, hdPid);
            db.AddParameter("@FnHD_Type", System.Data.SqlDbType.SmallInt, hdType);
            db.AddParameter("@FsHD_Title", System.Data.SqlDbType.NVarChar, hdTitle, 128);
            db.AddParameter("@FnHD_Status", System.Data.SqlDbType.SmallInt, hdStatus);
            db.AddParameter("@mediaList", System.Data.SqlDbType.VarChar, xml, -1);
            db.AddParameter("@FnOI_ID", System.Data.SqlDbType.VarChar, optor.openId);
            db.AddParameter("@FsOI_Name", System.Data.SqlDbType.NVarChar, optor.uiName, 32);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_ToHelperDoc(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            var data = _HelperOssDel(list.xConvertObjectToJson(false));
            return backJson(0, null, data);
        }
        public static List<object> _HelperOssDel(string urlList)
        {
            var list = new List<object>();
            if (urlList.Length > 0)
            {
                var oss = Helper.GetAliOssConfig();
                Aliyun.OSS.OssClient client = new Aliyun.OSS.OssClient(oss.endpoint, oss.accessKeyId, oss.accessKeySecret);
                var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(urlList, new[] { new { miUrl = "" } });
                foreach (var x in json)
                {
                    var url = x.miUrl.Replace("https://ynz1901.oss-cn-shanghai.aliyuncs.com/", "");

                    try
                    {
                        // 删除文件。
                        client.DeleteObject(oss.bucketName, url);
                    }
                    catch (Exception ex)
                    {
                        list.Add(new
                        {
                            code = 1,
                            errmsg = ex.Message,
                            miUrl = x.miUrl
                        });
                    }
                }
            };
            if (list.Count > 0)
            {
                var log = new YYS.LogModel("YYSService", "document", "_HelperOssDel", "删除共享空间文件失败");
                log.Add("dbHelper", list.xConvertObjectToJson(false));
                Helper.Log(log);
            }
            return list;
        }
        [HttpPost]
        [v3Authorize()]
        public JsonResult HelperOssDel()//删除共享空间 阿里云文件
        {
            //https://ynz1901.oss-cnhttps://40k6300z85.oicp.vip/api/pc/WxMpLogin/x_r2UUFO9cAEpTCoQgxcW1_vtJp3GaDFR0LjDnnJQVnlmna_gDyx4g5MqTzl2Nw8h_qDvEVG1jYHSYDgqUI8WQ-shanghai.aliyuncs.com/helper/%E6%98%9F%E5%A5%B3-%E6%94%BE%E7%BA%B5L.mp3https://40k6300z85.oicp.vip/api/pc/WxMpLogin/x_r2UUFO9cAEpTCoQgxcW1_vtJp3GaDFR0LjDnnJQVnlmna_gDyx4g5MqTzl2Nw8h_qDvEVG1jYHSYDgqUI8WQ
            var urlList = Request.Form["urlList"].xTrim();//填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。

            var list = new List<object>();
            if (urlList.Length > 0)
            {
                var oss = Helper.GetAliOssConfig();
                Aliyun.OSS.OssClient client = new Aliyun.OSS.OssClient(oss.endpoint, oss.accessKeyId, oss.accessKeySecret);
                var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(urlList, new[] { new { miUrl = "" } });
                foreach (var x in json)
                {
                    var url = x.miUrl.Replace("https://ynz1901.oss-cn-shanghai.aliyuncs.com/", "");
                    
                    try
                    {
                        // 删除文件。
                        client.DeleteObject(oss.bucketName, url);
                    }
                    catch (Exception ex)
                    {
                        list.Add(new {
                            code=1,
                            errmsg= ex.Message,
                            x.miUrl
                        });

                    }
                }
            };
            return backJson(0, null,list);
        }
        [HttpGet]
        [CompressHtml]
        public ActionResult helperShare()
        {
            return View("~/Views/pc/My/Component/helper.share.cshtml");
        }
        #endregion 帮助文档

        #region 姨妈助手
        [HttpPost]
        [v3Authorize(accessId = 3011)]
        public JsonResult menstruationList()
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var aBeginTime = Request.Form["beginTime"].xToDatetime("yyyy-MM-dd");
            var aEndTime = Request.Form["endTime"].xToDatetime("yyyy-MM-dd");
            var optor = Request.v3UnifiedUser();
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MenstruationList";
            db.IsProc = true;
            db.AddParameter("@aBeginTime", SqlDbType.DateTime, aBeginTime);
            db.AddParameter("@aEndTime", SqlDbType.DateTime, aEndTime);
            db.AddParameter("@Fs_OpenID", SqlDbType.NVarChar, optor.openId, 50);
            db.AddParameter("@Fs_OpenID_R", SqlDbType.NVarChar, optor.openId_R, 50);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.InputOutput);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                var obj = _courseToDictionary(sdr);
                list.Add(obj);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                list = list
            });
        }
        [HttpPost]
        [v3Authorize(accessId = 3011)]
        public JsonResult menstruationSave()
        {
            var optType = Request.Form["optType"].xTo<int>(-1); //0：新增；1：修改；2：删除  3.启用/停用        
            var Date = Request.Form["msDate"].xTrim().xToDatetime("yyyy-MM-dd");
            var Id = Request.Form["msId"].xTo<int>();
            var Mark = Request.Form["msMark"].xTrim();

            if (!optType.xRange(0, 1, 2)) return backJson(1, "无效参数.optType");
            if (optType > 0 && Id <= 0) return backJson(1, "无效参数.id");
            if (optType < 2)
            {
                if (!Date.HasValue) return backJson(1, "无效参数.date");
            };

            object data = null;
            var optor = Request.v3UnifiedUser();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MenstruationSave";
            db.IsProc = true;
            db.AddParameter("@optType", System.Data.SqlDbType.Int, optType);
            db.AddParameter("@msId", System.Data.SqlDbType.Int, Id);
            db.AddParameter("@msDate", System.Data.SqlDbType.Date, Date);
            db.AddParameter("@msMark", System.Data.SqlDbType.NVarChar, Mark, -1);
            db.AddParameter("@openId", System.Data.SqlDbType.NVarChar, optor.openId, 50);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data = (_courseToDictionary(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }
        #endregion 姨妈助手

        #region 日程
        [HttpPost]
        [v3Authorize(accessId = 501)]
        public JsonResult scheduleList()
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var aBeginTime = Request.Form["beginTime"].xToDatetime("yyyy-MM-dd");
            var aEndTime = Request.Form["endTime"].xToDatetime("yyyy-MM-dd");
            var optor = Request.v3UnifiedUser();
            var list = new List<object>();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_ScheduleList";
            db.IsProc = true;
            db.AddParameter("@aBeginTime", SqlDbType.DateTime, aBeginTime);
            db.AddParameter("@aEndTime", SqlDbType.DateTime, aEndTime);
            db.AddParameter("@Fs_OpenID", SqlDbType.NVarChar, optor.openId, 50);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.InputOutput);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                var obj = _courseToDictionary(sdr);
                list.Add(obj);
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                list = list
            });
        }
        [HttpPost]
        [v3Authorize(accessId = 501)]
        public JsonResult scheduleSave()
        {
            var optType = Request.Form["optType"].xTo<int>(-1); //0：新增；1：修改；2：删除  3.启用/停用        
            var schTitle = Request.Form["schTitle"].xTrim();
            var schDate = Request.Form["schDate"].xTrim().xToDatetime("yyyy-MM-dd");
            var schId = Request.Form["schId"].xTo<int>();
            var schMark = Request.Form["schMark"].xTrim();

            if (!optType.xRange(0, 1, 2)) return backJson(1, "无效参数.optType");
            if (optType > 0 && schId <= 0) return backJson(1, "无效参数.id");
            if (optType < 2)
            {
                if (schTitle.Length==0) return backJson(1, "无效参数.title");
                if (!schDate.HasValue) return backJson(1, "无效参数.date");
            };

            object data = null;
            var optor = Request.v3UnifiedUser();
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_ScheduleSave";
            db.IsProc = true;
            db.AddParameter("@optType", System.Data.SqlDbType.Int, optType);
            db.AddParameter("@schId", System.Data.SqlDbType.Int, schId);
            db.AddParameter("@schTitle", System.Data.SqlDbType.NVarChar, schTitle,64);
            db.AddParameter("@schDate", System.Data.SqlDbType.Date, schDate);
            db.AddParameter("@schMark", System.Data.SqlDbType.NVarChar, schMark,-1);
            db.AddParameter("@openId", System.Data.SqlDbType.NVarChar, optor.openId, 50);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data=(_courseToDictionary(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, data);
        }
        #endregion 日程

        #region 课程
        [HttpPost]
        [v3Authorize(accessId = 502)]
        public JsonResult getCourseInfoList() //课程列表 PC端
        {
            var pageIndex = Request.Form["pageIndex"].xTo<int>();
            var pageSize = Request.Form["pageSize"].xTo<int>();
            var FnCIL_Status = Request.Form["cilStatus"].xTo<short>(-1);
            var FsCIL_Name = Request.Form["cilName"].xTrim();
            var aBeginTime = Request.Form["beginTime"].xToDatetime("yyyy-MM-dd");
            var aEndTime = Request.Form["endTime"].xToDatetime("yyyy-MM-dd 23:59:59.997");
            var reqUser = Request.v3UnifiedUser();

            var list = new List<object>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_CourseInfoList";
            db.IsProc = true;
            db.AddParameter("@FsCIL_Name", SqlDbType.VarChar, FsCIL_Name, 128);
            db.AddParameter("@FnCIL_Status", SqlDbType.SmallInt, FnCIL_Status);
            db.AddParameter("@aBeginTime", SqlDbType.DateTime, aBeginTime);
            db.AddParameter("@aEndTime", SqlDbType.DateTime, aEndTime);
            db.AddParameter("@Fs_OpenID", SqlDbType.NVarChar, reqUser.openId, 50);
            db.AddParameter("@PageIndex", SqlDbType.Int, pageIndex, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", SqlDbType.Int, pageSize, parameterDirection: ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", SqlDbType.Int, 0, parameterDirection: ParameterDirection.InputOutput);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_courseToDictionary(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null, new
            {
                rowCount = db.OutParameters["RowCount"].xTo<int>(),
                pageIndex = db.OutParameters["PageIndex"].xTo<int>(),
                pageSize = db.OutParameters["PageSize"].xTo<int>(),
                list = list
            });
        }
        [HttpPost]
        [v3Authorize(accessId = 502)]
        public JsonResult courseInfoSave() //课程保存
        {
            var flag = Request.Form["optType"].xTo<short>(); //0：新增；1：修改；
            var FnCIL_ID = Request.Form["cilId"].xTo<int>();
            var FsCIL_Name = Request.Form["cilName"].xTrim();
            var cilRequire = Request.Form["cilRequire"].xTrim();
            var FfCIL_ClassHour = Request.Form["cilClassHour"].xTo<decimal>();
            var FdCIL_StartTime = Request.Form["cilStartTime"].xToDatetime();
            var FdCIL_FinishTime = Request.Form["cilFinishTime"].xToDatetime();
            var FsCIL_CoverPath = Request.Form["cilCoverPath"].xTrim();
            var lessonListStr = Request.Form["lessonList"].xTrim();//节次列表（json字符串）"[{"week":1,"cliId":1,"liId":1}]"
            var summaryListStr = Request.Form["summaryList"].xTrim().xUrlDecode();//课程简介（json字符串）
           
            var reqUser = Request.v3UnifiedUser();
            object data = null;

            XElement lessonXML = new XElement("xml");
            if (lessonListStr.Length > 0)
            {
                try
                {
                    var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(lessonListStr, new[] { new { week = 0, cliStartTime = "", cliFinishTime="", liName = "" } });
                    foreach (var x in json)
                    {
                        lessonXML.Add(new XElement("x",
                            new XElement("week", x.week),
                            new XElement("cliStartTime", x.cliStartTime),
                             new XElement("cliFinishTime", x.cliFinishTime),
                            new XElement("liName", x.liName)
                        ));
                    }
                }
                catch
                {
                    return backJson(1, "解析数据出错|节次");
                }
            }
                        
            XElement summaryXML = new XElement("xml");
            if (summaryListStr.Length > 0)
            {
                try
                {
                    var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(summaryListStr, new[] { new { miId = 0, miIndex = 0, miType = -1, miTitle = "", miUrl = "", miSize = "", miDuration = "" } });
                    foreach (var x in json)
                    {
                        summaryXML.Add(new XElement("x",
                                new XElement("miId", x.miId),
                                new XElement("miIndex", x.miIndex),
                                new XElement("miType", x.miType),
                                new XElement("miTitle", x.miTitle),
                                new XElement("miUrl", x.miUrl),
                                new XElement("miSize", x.miSize),
                                new XElement("miDuration", x.miDuration)
                            ));
                    }
                }
                catch
                {
                    return backJson(1, "解析数据出错|课程简介", summaryXML.ToString());
                }
            }
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_CourseInfoSave";
            db.IsProc = true;
            db.AddParameter("@Flag", SqlDbType.SmallInt, flag);
            db.AddParameter("@FnCIL_ID", SqlDbType.Int, FnCIL_ID);
            db.AddParameter("@FsCIL_Name", SqlDbType.VarChar, FsCIL_Name, 128);
            db.AddParameter("@FsCIL_Require", SqlDbType.VarChar, cilRequire, 10);
            db.AddParameter("@FfCIL_ClassHour", SqlDbType.Decimal, FfCIL_ClassHour, Precision: 10, Scale: 2);
            db.AddParameter("@FdCIL_StartTime", SqlDbType.DateTime, FdCIL_StartTime);
            db.AddParameter("@FdCIL_FinishTime", SqlDbType.DateTime, FdCIL_FinishTime);
            db.AddParameter("@FsCIL_CoverPath", SqlDbType.NVarChar, FsCIL_CoverPath, 1024);
            db.AddParameter("@lessonXML", SqlDbType.Xml, lessonXML.ToString(), -1);
            db.AddParameter("@summaryXML", SqlDbType.Xml, summaryXML.ToString(), -1);
            db.AddParameter("@FnUI_OptorID", SqlDbType.NVarChar, reqUser.openId,50);
            db.AddParameter("@FsUI_OptorName", SqlDbType.NVarChar, reqUser.uiName, 64);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                data=(_courseToDictionary(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, "",data);
        }
        [HttpPost]
        [v3Authorize(accessId = 502)]
        public JsonResult wxGetSchedule() //获取课表
        {
            var xDate = Request.Form["date"].xTrim().xFormatDateTime("yyyy-MM-dd");
            if (xDate == null) return backJson(1, "无效参数|date");
            DateTime date = (DateTime)xDate.xToDatetime("yyyy-MM-dd");
            if (date.Year <= 0 || date.Year > 9999) return backJson(1, "无效参数|year");
            if (date.Month <= 0 || date.Month > 12) return backJson(1, "无效参数|month");

            var reqUser = Request.v3UnifiedUser();

            var list = new List<object>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_GetSchedule";
            db.IsProc = true;
            db.AddParameter("@Year", SqlDbType.Int, date.Year);
            db.AddParameter("@Month", SqlDbType.Int, date.Month);
            db.AddParameter("@reqID", SqlDbType.NVarChar, reqUser.openId,50);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_courseToDictionary(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, null,list);
        }

        [HttpPost]
        [v3Authorize()]
        public JsonResult wxGetScheduleTaskList() //获取课表任务列表
        {
            var xDate = Request.Form["date"].xTrim().xFormatDateTime("yyyy-MM-dd");
            if (xDate == null) return backJson(1, "无效参数|date");

            var reqUser = Request.v3UnifiedUser();
            var list = new List<object>();

            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_GetScheduleTaskDetail";
            db.IsProc = true;
            db.AddParameter("@aDate", SqlDbType.DateTime, xDate);
            db.AddParameter("@openId", SqlDbType.NVarChar, reqUser.openId,50);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_courseToDictionary(sdr));
            };
            db.Exec();
            if (db.HasError) return _DBERROR(db);
            return backJson(0, "", list);
        }
        #endregion 课程

        /// <summary>
        /// 微信跳转pc
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [CompressHtml]
        public ActionResult WxMpLogin()
        {
            return View("~/Views/pc/WxMpLogin.cshtml");
            //return View("~/Views/pc/WxMpLogin.cshtml");
        }
        /// <summary>
        /// 视频共享
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [CompressHtml]
        public ActionResult videoShare()
        {
            var aResult = new ResultObj<object>();
            var list = new List<object>();
            var miGroupKey = "72CC2905-6A49-46F9-9598-7391B2F7667D";
            var pageIndex = Request.RequestContext.RouteData.Values["id"].xTo<int>(1);//页码
            var pageSize = 10;//每页记录数
            var db = Helper.GETdbHelper(dbHelper.EnumServer.Local, dbHelper.ExecType.WhileRead, DefaultValue.DataBase);
            db.CmdText = "PR_PRC_MediaInfoList";
            db.IsProc = true;
            db.AddParameter("@FsMI_GroupKey", SqlDbType.VarChar, miGroupKey, 128);
            db.AddParameter("@PageIndex", System.Data.SqlDbType.Int, pageIndex, parameterDirection: System.Data.ParameterDirection.InputOutput);
            db.AddParameter("@PageSize", System.Data.SqlDbType.Int, pageSize, parameterDirection: System.Data.ParameterDirection.InputOutput);
            db.AddParameter("@RowCount", System.Data.SqlDbType.Int, 0, parameterDirection: System.Data.ParameterDirection.Output);
            db.NeedOutError = true;
            db.FuncRead = sdr =>
            {
                list.Add(_TomediaList(sdr));
            };
            db.Exec();
            if (db.HasError) return View("Result", new YYS.ResultModel() { Icon = 5, Title = "查询失败", Msg = db.Error });
            ViewData["list"] = list;
            //return View("Result", new YYS.ResultModel() { Icon = 5, Title = "操作失败", Msg = "缺少必要的参数" });
            return View("~/Views/pc/helper/video.share.cshtml");
        }
        #endregion PC

        //SendEmail("smtp.example.com", 587, "your-email@example.com", "your-password", "recipient@example.com", "Test Email", "This is the email body.");
        [HttpGet]
        [CompressHtml]
        public ActionResult SendEmail()
        {
            //WYfk8Hsn3jkJ2nZD
            string fromEmail = DefaultValue.QQ_Email;
            string password = DefaultValue.QQ_SMTP;
            string toEmail = Request.QueryString["toEmail"].xTrim();
            string subject = Request.QueryString["title"].xTrim();
            string body = Request.QueryString["message"].xTrim().xUrlDecode();
            string filePath = Request.QueryString["filePath"].xTrim();
            var optType = Request.QueryString["optType"].xTo<int>();
            var message = "";
            if (!string.IsNullOrWhiteSpace(body))
            {
                if (optType == 1)
                {
                    try
                    {
                        var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(body, new[] { new { schTitle = "", DATE = "", schMark = "" } });
                        foreach (var x in json)
                        {
                            message += "<p>【{0}】时间：{1} 备注：{2}</p>".xFormat(x.schTitle, x.DATE, x.schMark);
                        }
                    }
                    catch
                    {
                        return Json("解析数据出错 | 日程提醒", JsonRequestBehavior.AllowGet);
                    };
                }
                if (optType == 2)
                {
                    try
                    {
                        var json = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(body, new[] { new { FsCIL_Name = "", DATE = "", FdCLI_StartTime = "", FdCLI_FinishTime = "", FsLI_Name = "" } });
                        foreach (var x in json)
                        {
                            message += "<p>【{0}】时间：{1}（{2}-{3}）地点：{4}</p>".xFormat(x.FsCIL_Name,x.DATE,x.FdCLI_StartTime,x.FdCLI_FinishTime,x.FsLI_Name);
                        }
                    }
                    catch
                    {
                        return Json("解析数据出错 | 上课提醒", JsonRequestBehavior.AllowGet);
                    };
                }
            }
            else
            {
                message = body;
            };
            try
            {               
                // 创建邮件消息
                // 创建邮件对象
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(fromEmail, "小杨");
                mail.To.Add(new MailAddress(toEmail));
                mail.Subject = subject;
                mail.Body = "<html><body>"+ message + "</body></html>";
                mail.IsBodyHtml = true;

                // 添加附件
                if (!string.IsNullOrEmpty(filePath))
                {
                    Attachment attachment = new Attachment(filePath);
                    mail.Attachments.Add(attachment);
                }

                // 创建SMTP客户端
                SmtpClient smtpClient = new SmtpClient("smtp.qq.com", 587);
                smtpClient.Credentials = new NetworkCredential(fromEmail, password);
                smtpClient.EnableSsl = true;

                // 发送邮件
                smtpClient.Send(mail);
                return Json("邮件发送成功" , JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(fromEmail+"邮件发送失败：" + ex.ToString(), JsonRequestBehavior.AllowGet);
            }
        }
    }
}